package com.frame.utils;

import java.io.Serializable;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbcp.BasicDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import com.frame.cache.CacheManager;

public class QueryHelper {
	
	private BasicDataSource dataSource;
	
	public void setDataSource(BasicDataSource dataSource) {
		System.out.println(" do this? dataSource ------------------------------- " + dataSource);
		this.dataSource = dataSource;
	}

	public BasicDataSource getDataSource() {
		return dataSource;
	}
	/*
	public QueryHelper createQr(){
		return new QueryHelper();
	}*/
	
	private static QueryRunner qr = new QueryRunner();

	/**
	 * ���¡����롢ɾ��ʵ��
	 * @param sql
	 * @param params
	 */
	public Integer update(String sql, Object ... params) throws SQLException{
		return update(dataSource.getConnection(), sql, params);
	}
	
	public static Integer update(Connection conn, String sql, Object ... params) throws SQLException {
		return qr.update(conn, sql, params);
	}
	
	/** ��ȡĳ������ 
	 * @throws SQLException */
	@SuppressWarnings("unchecked")
	public <T> T read(Class<T> beanClass, String sql, Object ... params) throws SQLException{
		System.out.println("--- check pool --- " + dataSource);
		return (T) qr.query(dataSource.getConnection(), sql, new BeanHandler(beanClass), params);
	}
	
	/** ʹ�û��� 
	 * @throws SQLException */
	@SuppressWarnings("unchecked")
	public <T> T read(Class<T> beanClass, String cache, Serializable key, String sql, Object ... params) throws SQLException{
		T obj = (T) CacheManager.get(cache, key);
		if(obj == null){
			obj = read(beanClass, sql, params);
			CacheManager.set(cache, key, (Serializable)obj);
		}
		return obj;
	}
	
	/** ��ȡ�����б?�޷�ҳ 
	 * @throws SQLException */
	@SuppressWarnings("unchecked")
	public <T> List<T> query(Class<T> beanClass, String sql, Object ... params) throws SQLException{
		return (List<T>) qr.query(dataSource.getConnection(), sql, new BeanListHandler(beanClass), params);
	}

}
